import React, { useEffect, useState } from 'react';
import { Table, Tag, Space, Button, Switch, notification, Drawer, Form, Input, Select, Tree } from 'antd';
import { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import { useNavigate } from 'react-router-dom';
import service from '../../../api';
import _, { set, values } from 'lodash';
import "./index.scss"



function Admin(props: any) {
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [adminList, setAdminList] = useState([]);
  var [checkedKeys, setCheckedKeys] = useState([]);
  var [adminid, setAdminid] = useState('');

  interface DataType {
    key: any;
    adminname: string;
    adminid: string;
    role: number;
    img: string;
  }
  //获取管理员列表
  var requsetAdminList = async () => {
    var res = await service.admin.adminList();
    console.log(res);
    setAdminList(res.data.data);
  }
  useEffect(() => {
    requsetAdminList();
  }, [])
  //删除管理员
  const deleteAdmin = async (adminid: any) => {
    const res = await service.admin.adminDel({ adminid });
    notification.destroy()
    console.log(res);
    if (res.data.code === '200') {
      notification.success({ message: '删除成功' });
      requsetAdminList();
    }
    //深拷贝
    var newAdminList = _.cloneDeep(adminList);
    var index = newAdminList.findIndex((item: any) => item.adminid === adminid);
    newAdminList.splice(index, 1);
    setAdminList(newAdminList);
  }

  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
    //清空表单
    form.resetFields();
    checkedKeys = [];
    setCheckedKeys(checkedKeys);
    setAdminid('');
  }
  const handleChange = (value: any) => {
    console.log(`selected ${value}`);
  }

  const changeAdmin = (values: any) => {
    setOpen(true);
    //回显
    form.setFieldsValue({
      adminname: values.adminname,
      role: values.role,
      adminid: values.adminid,
      password: values.password,
    })
    setCheckedKeys(values.checkedKeys);
    setAdminid(values.adminid);
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      key: 'index',
      dataIndex: 'index',
      render: (_, text, index) => <div>{index + 1}</div>,
    },
    {
      title: '账号',
      key: 'adminname',
      dataIndex: 'tel',
      render: (_, record, index) => <div>{record.adminname}</div>,
    },
    {
      title: '权限',
      key: 'role',
      dataIndex: 'link',
      render: (_, record, index) =>
        <div>{record.role === 1 ? <Tag color="success">管理员</Tag> : <Tag color="processing">超级管理员</Tag>}</div>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, index) => (
        <div className='twoButtn'>
          <Button type='primary' size='small' onClick={() => changeAdmin(record)}>编辑</Button>
          <Button type='primary' size='small' danger={true} onClick={() => deleteAdmin(record.adminid)}>删除</Button>
        </div>
      ),
    },
  ];

  const treeData: DataNode[] = [
    {
      title: '轮播图管理',
      key: '1',
      children: [
        {
          title: '轮播图列表',
          key: '1-1',
        },
      ]
    },

    {
      title: '账号管理',
      key: '2',
      children: [
        { title: '管理员列表', key: '2-1' },
      ],
    },
    {
      title: '产品管理',
      key: '3',
      children: [
        { title: '产品列表', key: '3-1' },
        { title: '秒杀列表', key: '3-2' },
        { title: '推荐列表', key: '3-3' },
        { title: '筛选列表', key: '3-4' },
      ],
    },
    {
      title: '数据可视化',
      key: '4',
      children: [
        { title: 'echarts使用', key: '4-1' },
      ],
    },
    {
      title: '编辑器',
      key: '5',
      children: [
        { title: '富文本编辑器', key: '5-1' },
      ],
    },
    {
      title: 'excel管理',
      key: '6',
      children: [
        { title: 'excel导入', key: '6-1' },
        { title: 'excel导出', key: '6-2' },
      ],
    },
    {
      title: '地图管理',
      key: '7',
      children: [
        { title: '百度地图', key: '7-1' },
      ],
    },
  ];
  const onCheck = (checkedKeysValue: any) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
    //保存权限到form表单
    form.setFieldsValue({ 'checkedKeys': checkedKeysValue });
  };
  const onFinish = async (values: any) => {
    console.log('Success:', values);
    if (adminid) {
      const res = await service.admin.adminUpdate(values);
      console.log(res);
      if (res.data.code === '200') {
        notification.success({ message: '编辑成功' });
        requsetAdminList();
      }
      setOpen(false);
    } else {
      const res = await service.admin.adminAdd(values);
      console.log(res);
      if (res.data.code === '200') {
        notification.success({ message: '添加成功' });
        requsetAdminList();
      }
      setOpen(false);
    }
  };

  return (
    <div className='adminbiao'>
      <Button className='addbanner' type="primary" onClick={showDrawer}>添加管理员+</Button>
      <Table className='bannerbg' columns={columns} dataSource={adminList} />
      <Drawer title={adminid ? '编辑管理员' : '添加管理员'} placement="right" onClose={onClose} open={open}>
        <Form
          form={form}
          name="basic"
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="用户"
            name="adminname"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input disabled={adminid != ''} />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password disabled={adminid != ''} />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[{ required: true, message: '请选择管理员!' }]}
          >
            <Select
              style={{ width: 120 }}
              onChange={handleChange}
              options={[
                { value: 1, label: '管理员' },
                { value: 2, label: '超级管理员' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="权限"
            name="checkedKeys"
            rules={[{ required: true, message: '请选择管理员权限!' }]}
          >
            <Tree
              checkable
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              treeData={treeData}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              {adminid ? '编辑管理员' : '添加管理员'}
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}

export default Admin;